package com.qf.controller;
import com.github.pagehelper.PageInfo;
import com.mysql.jdbc.StringUtils;
import com.qf.bean.Dept;
import com.qf.bean.Major;
import com.qf.bean.User;
import com.qf.enums.PageEnum;
import com.qf.exception.ExamException;
import com.qf.service.DeptService;
import com.qf.service.MajorService;
import com.qf.service.UserService;
import com.qf.utils.ExcelUtilz
import com.qf.vo.ResultVo;
import com.qf.vo.UserAllVo;
import com.qf.vo.UserDetailVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
@Controller
@Slf4j
public class userController {
    @Autowired
    private UserService userService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private MajorService majorService;
    //跳转到进行充值页面
    @RequestMapping("/tiaozhuanchonghz")
    public String tizoahzuan(String username,ModelMap map){
       /* System.out.println(realname);*/
    User user= userService.findByUsername(username) ;
    int money = user.getMoney();
        String realname = user.getRealname();
        map.addAttribute("yuE",money);
        map.addAttribute("username",username);
        map.addAttribute("realname",realname);
        return "/xiugaiyue";
    }
    //进行充值
    @RequestMapping("/chongzhi")
    @ResponseBody
        public ResultVo choongzhi(String username,int qian){
        System.out.println(username);
        System.out.println(qian);
        User user = userService.findByUsername(username);
        //用户的账户历史的钱
        int money = user.getMoney();
        money=money+qian;
     userService.updateqianBy(username,money);
     if(money>100){
         //向useeroles表修改历史的rolenme
        int i= userService.updaterolenaemBy(username);
         return new ResultVo(0,"恭喜您已经成为会员","");
     }else {
         return new ResultVo(7,"对不起您的余额不足！尚且还不是会员","");
     }

    }
    //导出的数据
    @RequestMapping("/daochu")
    public void daochu(int[]userid, HttpServletResponse response){
        System.out.println(userid);
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        List<UserAllVo> userAllVolist = userService.findByids(userid);
        //2.导出数据
        try {
            ExcelUtils.createFirst("用户信息");
            ExcelUtils.createOthers(userAllVolist);
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
            ExcelUtils.export(new FileOutputStream("d://"+(format.format(new Date()))+".xls"));
            writer.print("<script>alert('导出成功');location.href='/list'</script>");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //跳转到修改密码的页面
   @RequestMapping("/updatePs")
    public  String upps(String realname,ModelMap map){
       UserDetailVo userDetailVo = userService.finBy(realname);
       String password = userDetailVo.getPassword();
       int userid = userDetailVo.getUserid();
      /* System.out.println(userid);*/
       map.addAttribute("userid",userid);
       map.addAttribute("password",password);
       return "upPs";

    }
    //执行修改密码
    @RequestMapping("/updatePasswod")
    @ResponseBody
    public ResultVo update(String oldpassword,String newpassword ,String repassword,String password ,int userid){
        if(!oldpassword.equals(password)){
            return new ResultVo(55,"您输入的密码有误，请重新输入","");
        }
     if(!newpassword.equals(repassword)){
         return  new ResultVo(33,"两次输入的密码不一致","");
     }

     User user=new User();
     user.setPassword(newpassword);
     user.setUserid(userid);
 int i= userService.updatE(user);
 if(i>0){
     return new ResultVo(0,"","");
 }else {
     return new ResultVo(66,"修改失败了","");
 }
    }
    //执行编辑
    @RequestMapping("/updatee")
            public String updateee(User user){
        System.out.println(user);
         int i=  userService.update(user);
      if(i>0){
          return "redirect:/list";
      }else {
          return "redirect:/update";
      }
    }
    //回显并得到所有部门
    @RequestMapping("/update")
    public String huixian(String realname,ModelMap map){
       List<Dept> deptlist= deptService.findAll();
      map.addAttribute("dlist",deptlist);
        List<Major> all = majorService.findAll();
        map.addAttribute("mlist",all);
        UserDetailVo userDetailVo = userService.finBy(realname);
    /*    System.out.println(userDetailVo);*/
        map.addAttribute("ulist",userDetailVo);
        return "update-list";
    }

    //跳转到展示用户基本信息的页面

    @RequestMapping("/list")
    public String findList(ModelMap map, @RequestParam(defaultValue = "1") int index,@RequestParam(defaultValue = "") String deptname,@RequestParam(defaultValue = "") String realname){
      PageInfo<UserAllVo> pageInfo= userService.findUserAll(index , PageEnum.PAGESIZE.getSize(),deptname,realname);
    /*    System.out.println(userAllVo);*/
   map.addAttribute("pageInfo",pageInfo);
   //储存查询条件
        map.put("deptname",deptname);
        map.put("realname",realname);
   return "user-list";
    }
    //异步校验用户名
    @RequestMapping("/check-realname")
    @ResponseBody
    public ResultVo yibu(String realname){
        System.out.println(realname);
      User user=  userService.findBy(realname);
        if(user==null){
            return new ResultVo(0,"","");
        }
        return  new ResultVo(1,"","");
    }
    //充值的时候检查用户名
    @RequestMapping("/check-username")
    @ResponseBody
    public  ResultVo jian(String username){
        User user = userService.findByUsername(username);
       if(user==null){
           return new ResultVo(0,"","");
       }else {
           return new ResultVo(3,"","");
       }
    }

    @RequestMapping("/index-ui")
    public String index(){
        return "index1";

    }
//添加用户
   @RequestMapping("/insert")
   @ResponseBody
    public ResultVo insert(User user){
       int i= userService.save(user);
      return new ResultVo(0,"","");
    }
    //删除用户
    @RequestMapping("/del")
    public String  del(String realname){
      int i= userService.del(realname);
      if(i>0){

          return "redirect:/list";
      }else{
          return null;
      }
    }
    //展示所有用户的详细xinxi
    @RequestMapping("/user/detail")
    public String detail(String realname,ModelMap map){
      UserDetailVo userDetailVo= userService.finBy(realname);
        /*System.out.println(userDetailVo);*/
      map.addAttribute("ulist",userDetailVo);
      return "detail-list";
    }
    //跳转到登录的首页
    @RequestMapping("/login-ui")
    public String loginUi(){
        return "login";
    }
//用shiro做登录
    @RequestMapping("/login")
    @ResponseBody
    public ResultVo login(String username,String password){
       if(StringUtils.isNullOrEmpty(username)||StringUtils.isNullOrEmpty(password)){
         log.info("用户名或者密码不能为空");
         throw new ExamException(78,"用户名或者密码不能为空");
       }
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(new UsernamePasswordToken(username,password));
        }catch (UnknownAccountException ue){
            throw new ExamException(91,"登陆失败，用户名错误");
        }catch (IncorrectCredentialsException ie){
            throw new ExamException(91,"登陆失败，密码错误");
        }
        return new ResultVo(0,"","");
    }
    //获得用户的真实姓名
/*    public void getname(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();
    //获得用户的姓名
        String username = user.getUsername();*/

 /*   }*/
     @GetMapping("/unauthorized")
    public String unauthorized(String realname,ModelMap map){
         System.out.println(realname);

         return "401";
    }

}

